﻿using EnterpriseWebsiteEntity;
using EnterpriseWebsiteUtil.Helper;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Linq;

namespace EnterpriseWebsiteBLL
{
    public class ProductService
    {
        public readonly SqlSugarClient _db;

        public ProductService(SqlSugarHelper sqlSugarHelper)
        {
            _db = sqlSugarHelper.sugarClient;
        }

        public async Task<List<ProductEntity>> GetAllProductAsync(RefAsync<int> total, int index = 0, int pageSize = 20, int category = 0, string keyword = null)
        {
            var queryable = _db.Queryable<ProductEntity>();

            if (category != 0)
            {
                queryable = queryable.Where(a => a.CategoryId == category);
            }

            if (!string.IsNullOrWhiteSpace(keyword))
            {
                queryable = queryable.Where(a => a.ProductName.Contains(keyword));
            }

            queryable.OrderByDescending(q=> q.HomeShow).OrderByDescending(q => q.CreateDate);

            return await queryable.ToPageListAsync(index, pageSize, total);
        }

        public async Task<List<ProductEntity>> GetAllProductAsync(int categorieId, RefAsync<int> total, bool publish = true,bool? homeShow = null, int index = 0, int pageSize = 20)
        {
            return await _db.Queryable<ProductEntity>()
                .LeftJoin<ProductCategorieEntity>((a,b)=> a.CategoryId == b.Id)
                .Where((a, b) => a.Publish == publish && b.Enable)
                .WhereIF(categorieId != 0, (a,b)=> a.CategoryId == categorieId && b.Id == categorieId)
                .WhereIF(homeShow != null,(a,b)=> a.HomeShow == homeShow)
                .OrderByDescending((a, b) => a.HomeShow)
                .OrderByDescending((a, b) => a.CreateDate)
                .ToPageListAsync(index, pageSize, total);
        }

        public async Task<ProductEntity> GetSingleProductByIdAsync(int  id,bool publish = true)
        {
            return await _db.Queryable<ProductEntity>()
                .LeftJoin<ProductCategorieEntity>((a, b) => a.CategoryId == b.Id)
                .Where((a, b) => a.Publish == publish && b.Enable && a.Id == id)
                .FirstAsync();
        }

        public async Task<ProductEntity> GetSingleProductByProductIdAsync(string productID,int? ignoreId = null)
        {
            return await _db.Queryable<ProductEntity>()
                .Where(p=> p.ProductID.Equals(productID))
                .WhereIF(ignoreId != null, p=> p.Id != ignoreId)
                .FirstAsync();
        }

        public async Task DeleteProductById(int id)
        {
            var entity =  await GetProductSingleByIdAsync(id);
            if (entity == null)
            {
                throw new Exception($"ID {id} 商品不存在");
            }
            await _db.Deleteable<ProductEntity>().In(id).ExecuteCommandAsync();
        }

        public async Task<ProductEntity> AddProductAsync(ProductEntity  product)
        {
            #region 参数校验
            if (!string.IsNullOrEmpty(product.ProductID))
            {
                var productDB = await GetSingleProductByProductIdAsync(product.ProductID);
                if (productDB != null)
                {
                    throw new Exception($"产品编号\"{product.ProductID}\"已存在，请确保产品编号的唯一性");
                }
            }
            if (string.IsNullOrEmpty(product.ProductName))
            {
                throw new Exception("商品名称，必须填写");
            }
            if (product.ProductName.Length > 100)
            {
                throw new Exception("商品名称，不能超过100个字数");
            }
            if (!string.IsNullOrEmpty(product.DetailImageUrls))
            {
                var images = JsonConvert.DeserializeObject<List<string>>(product.DetailImageUrls);
                if (images.Count > 0)
                {
                    product.MainImageUrl = images.FirstOrDefault();
                }
                else
                {
                    product.MainImageUrl = "";
                }
            }
            else
            {
                product.DetailImageUrls = "[]";
                product.MainImageUrl = "";
            }
            if (product.CategoryId == 0)
            {
                throw new Exception("请选择商品类目");
            }
            if (product.ShortDescription.Length > 500)
            {
                throw new Exception("商品简单描述，不能超过500个字数");
            }
            #endregion

            product.UpdateDate = DateTime.Now;
            product.CreateDate = DateTime.Now;
            return await _db.Insertable(product)
                .ExecuteReturnEntityAsync();
        }

        public async Task<ProductEntity> UpdateProductAsync(ProductEntity product)
        {
            #region 参数校验
            if (product.Id == 0)
            {
                throw new Exception("商品ID不能为空");
            }
            if (!string.IsNullOrEmpty(product.ProductID))
            {
                var productDB = await GetSingleProductByProductIdAsync(product.ProductID,product.Id);
                if (productDB != null)
                {
                    throw new Exception($"产品编号\"{product.ProductID}\"已存在，请确保产品编号的唯一性");
                }
            }
            if (string.IsNullOrEmpty(product.ProductName))
            {
                throw new Exception("商品名称，必须填写");
            }
            if (product.ProductName.Length > 100)
            {
                throw new Exception("商品名称，不能超过100个字数");
            }
            if (!string.IsNullOrEmpty(product.DetailImageUrls))
            {
                var images = JsonConvert.DeserializeObject<List<string>>(product.DetailImageUrls);
                if (images.Count > 0)
                {
                    product.MainImageUrl = images.FirstOrDefault();
                }
                else
                {
                    product.MainImageUrl = "";
                }
            }
            else
            {
                product.DetailImageUrls = "[]";
                product.MainImageUrl = "";
            }
            if (product.CategoryId == 0)
            {
                throw new Exception("请选择商品类目");
            }
            if (product.ShortDescription.Length > 500)
            {
                throw new Exception("商品简单描述，不能超过500个字数");
            }
            #endregion

            product.UpdateDate = DateTime.Now;
            return await _db.Updateable(product)
                .ExecuteCommandAsync() > 0 ? product : null;

        }

        public async Task<ProductEntity> GetProductSingleByIdAsync(int id)
        {
            return await _db.Queryable<ProductEntity>()
                .Where(p => p.Id == id)
                .FirstAsync();
        }

        public async Task ChangePublish(int id, bool publish)
        {
            var entity = await GetProductSingleByIdAsync(id);
            if (entity == null)
            {
                throw new Exception($"Id {id} 商品不存在");
            }
            entity.Publish = publish;
            _db.Updateable(entity).ExecuteCommand();
        }
        
        public async Task ChangeHomeShow(int id, bool state)
        {
            var entity = await GetProductSingleByIdAsync(id);
            if (entity == null)
            {
                throw new Exception($"Id {id} 商品不存在");
            }
            entity.HomeShow = state;
            _db.Updateable(entity).ExecuteCommand();
        }

        public async Task<List<ProductEntity>> GetProductByCategorieId(int categorieId)
        {
            return await _db.Queryable<ProductEntity>()
                .Where(p => p.CategoryId == categorieId)
                .ToListAsync();
        }

        public async Task<List<ProductEntity>> GetProductByCurrencies(int currenciesId)
        {
            return await _db.Queryable<ProductEntity>()
                .Where(p => p.Currencies == currenciesId)
                .ToListAsync();
        }
    }
}
